package moe.oil.db.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import moe.oil.dto.school.CommentsDTO;
import moe.oil.entity.BaseEntity;

import javax.persistence.*;
import java.time.Instant;

/**
 * @author om on 2020/04/24.
 * 留言表
 */

@Table
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Comments implements BaseEntity<CommentsDTO> {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "comments_seq")
    private Long commentId;

    @ManyToOne(cascade = {CascadeType.MERGE,CascadeType.REMOVE})
    private User users;

    //todo check parent id must exist and not this id
    @OneToOne(cascade = CascadeType.ALL)
    @JsonIgnore
    @JoinColumn(name = "parent_id")
    private Comments parentId;

    @Column(name = "create_time")
    private Instant createTime;

    @Column(name = "message")
    private String message;

    @JoinColumn(name = "schools")
    @JsonIgnore
    @ManyToOne(cascade = { CascadeType.MERGE,CascadeType.REMOVE})
    private School school;

    @Override
    public String toString() {
        return String.format(
                "Comments[id=%s, userId=%s, parentId=%s, createTime=%s, message=%s, school=%s]",
                commentId, users, parentId, createTime, message, school);
    }

    @Override
    public CommentsDTO convert() {
        return new CommentsDTO()
                .setCommentId(commentId)
                .setCreateTime(createTime)
                .setMessage(message)
                .setSchoolDTO(school != null ? school.convert() : null)
                .setUserDTO(users != null ? users.convert() : null);
    }

    public Comments(CommentsDTO dto) {
        this.createTime = dto.getCreateTime();
        this.message = dto.getMessage();
        this.commentId = dto.getCommentId();
        if (dto.getSchoolDTO() != null) {
            this.school = new School(dto.getSchoolDTO());
        }
        if (dto.getUserDTO() != null) {
            this.users = new User(dto.getUserDTO());
        }
    }
}
